package com.originskyseed.platform.user.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.originskyseed.platform.user.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.common.annotation.SysLog;
import com.originskyseed.platform.common.api.util.QueryAppUtil;
import com.originskyseed.platform.common.utils.JsonUtils;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.util.bean.ExportExcelUtil;
import com.originskyseed.platform.user.i18n.UserResponseMsg;
import com.originskyseed.platform.user.model.Anchor;
import com.originskyseed.platform.user.model.AnchorGroup;
import com.originskyseed.platform.user.model.AnchorRelateAnnex;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.Family;
import com.originskyseed.platform.user.model.TaskSelectAnchorVO;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.vo.request.AnchorRequestVO;

/**
 * 主播信息Controller类（OSI_ANCHOR）
 *
 * @author
 */
@Controller
@RequestMapping("/anchor")
@BaseLocaleResource(localeFileName = "i18n_user")
public class AnchorController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(AnchorController.class);

	@DubboReference
	private IAnchorService anchorService;

	@DubboReference
	private IDeptService deptService;

	@DubboReference
	private IFamilyService familyService;

	@DubboReference
	private IUserInfoService userInfoService;

	@DubboReference
	private IAnchorRelateAnnexService anchorRelateAnnexService;

	@DubboReference
	private IAnchorGroupService groupService;

	@DubboReference
	private IAnchorRelateGroupService anchorRelateGroupService;

	@DubboReference
	private IPlayerRelateConsumeService playerRelateConsumeService;

	@DubboReference
	private IAnchorRelateByoFansService anchorRelateByoFansService;

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/anchorList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<Anchor>> anchorList(HttpServletRequest request) {
		BaseResponseBody<BasePage<Anchor>> result = null;
		try {
			// 请求对象
			AnchorRequestVO requestVO = this.getParameterBean(AnchorRequestVO.class);
			String anchorNickName = request.getParameter("anchorNickName") == null ? "" : request.getParameter("anchorNickName").toString();
			Map<String, Object> paramsMap = requestVO.toMap();
			if (StringUtils.isNotEmpty(anchorNickName)) {
				paramsMap.put("anchorNickName", anchorNickName);
			}
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);

			// Family family = familyService.selectByUserId(userInfo.getId());
			// 分页查询
			BasePage<Anchor> page = new BasePage<Anchor>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.anchorService.selectAnchorInFoListByPage(paramsMap, page, userInfo);
			result = new BaseResponseBody<BasePage<Anchor>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<Anchor>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 主播管理类主播列表信息导出Excel
	 *
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/anchorListToExcel.json")
	@SysLog(module = "主播列表信息", operationDesc = "主播列表信息导出excel")
	public void anchorListToExcel(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<Anchor> list = null;
			AnchorRequestVO requestVO = this.getParameterBean(AnchorRequestVO.class);
			requestVO.setIsDel(0);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			Family family = familyService.selectByUserId(userInfo.getId());
			if (family != null) {
				requestVO.setFamilyId(family.getFamilyId());
				list = this.anchorService.selectListToExcel(requestVO.toMap());
			}
			// excel标题
			String[] title = { "主播ID", "主播昵称", "签约形式", "直播等级（即视频等级）", "粉丝量", "当前状态" };
			// excel文件名
			String fileName = "主播信息列表.xls";
			// sheet名
			String sheetName = "主播信息";
			String[][] values = new String[list.size()][];

			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					values[i] = new String[title.length];
					Anchor obj = list.get(i);
					values[i][0] = obj.getAnchorId() == null ? "" : obj.getAnchorId();
					values[i][1] = obj.getAnchorNickName() == null ? "" : obj.getAnchorNickName();
					/*
					 * if(obj.getSignContractType() == 0){ values[i][2] = "对公主播"; }else if(obj.getSignContractType() == 1){ values[i][2] = "对私主播"; }else { values[i][2] = " "; }
					 */
					values[i][3] = obj.getLiveRating() == null ? "" : obj.getLiveRating().toString();
					values[i][4] = obj.getNumberOfFans() == null ? "" : obj.getNumberOfFans().toString();
					if (obj.getStatus() == 0) {
						values[i][5] = "正常";
					} else if (obj.getStatus() == 1) {
						values[i][5] = "警告";
					} else if (obj.getStatus() == 2) {
						values[i][5] = "封禁恢复";
					} else if (obj.getStatus() == 3) {
						values[i][5] = "永久封禁";
					} else {
						values[i][5] = " ";
					}
				}
			}
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 选择指派人主播信息列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectAnchorMaintainList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" }) // type 1公会部门下
	public BaseResponseBody<BasePage<TaskSelectAnchorVO>> selectAnchorMaintainList(HttpServletRequest request) {
		BaseResponseBody<BasePage<TaskSelectAnchorVO>> result = null;
		try {
			// 请求对象
			AnchorRequestVO requestVO = this.getParameterBean(AnchorRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 公会部门下
			BasePage<TaskSelectAnchorVO> page = new BasePage<TaskSelectAnchorVO>(requestVO.getPageNo(), requestVO.getPageSize());
			if (userInfo.getSourceSys() == 1) { // 内容平台
				if (requestVO.getType() != null && requestVO.getType() == 1) {
					List<String> deptIdList = new ArrayList<>();
					Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
					this.selectDeptSon(dept.getCode(), deptIdList);
					requestVO.setDeptIdList(deptIdList);
					page = this.anchorService.selectMaintainAnchorListByPage(requestVO.toMap(), page);
				}
			}
			if (userInfo.getSourceSys() == 0) { // 开放平台
				page = this.anchorService.selectMaintainAnchorListByPage(requestVO.toMap(), page);
			}
			// 分页查询
			result = new BaseResponseBody<BasePage<TaskSelectAnchorVO>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<TaskSelectAnchorVO>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 主播信息导出Excel模板
	 *
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@GetMapping("/anchorInfoToExcelModel.json")
	@SysLog(module = "主播墙模块", operationDesc = "主播信息导出excel模板")
	public void anchorInfoToExcelModel(HttpServletRequest request, HttpServletResponse response) {
		try {
			// excel标题
			String[] title = { "主播ID", "主播昵称", "主播封面地址", "主播头像地址", "签约形式", "直播等级（即视频等级）", "粉丝量", "主播技能度" };
			// excel文件名
			String fileName = "家族的主播信息导出模板.xls";
			// sheet名
			String sheetName = "家族的主播信息导出模板";
			String[][] values = new String[0][];
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 主播信息导出Excel
	 *
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/anchorInfoToExcel.json")
	@SysLog(module = "主播墙模块", operationDesc = "主播信息导出excel")
	public void anchorInfoToExcel(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<Anchor> list = null;
			AnchorRequestVO requestVO = this.getParameterBean(AnchorRequestVO.class);
			requestVO.setIsDel(0);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			Family family = familyService.selectByUserId(userInfo.getId());
			if (family != null) {
				requestVO.setFamilyId(family.getFamilyId());
				list = this.anchorService.selectListToExcel(requestVO.toMap());
			}
			// excel标题
			String[] title = { "主播ID", "主播昵称", "主播封面图片地址", "主播头像图片地址", "签约形式", "直播等级（即视频等级）", "粉丝量", "主播技能度" };
			// excel文件名
			String fileName = "家族的主播信息.xls";
			// sheet名
			String sheetName = "家族的主播信息";
			String[][] values = new String[list.size()][];

			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					values[i] = new String[title.length];
					Anchor obj = list.get(i);
					values[i][0] = obj.getAnchorId() == null ? "" : obj.getAnchorId();
					values[i][1] = obj.getAnchorNickName() == null ? "" : obj.getAnchorNickName();
					values[i][2] = obj.getAnchorCover() == null ? "" : obj.getAnchorCover();
					values[i][3] = obj.getAnchorHeadPortrait() == null ? "" : obj.getAnchorHeadPortrait();
					/*
					 * if(obj.getSignContractType() == 0){ values[i][4] = "对公主播"; }else if(obj.getSignContractType() == 1){ values[i][4] = "对私主播"; }else { values[i][4] = " "; }
					 */
					values[i][5] = obj.getLiveRating() == null ? "" : obj.getLiveRating().toString();
					values[i][6] = obj.getNumberOfFans() == null ? "" : obj.getNumberOfFans().toString();
					values[i][7] = obj.getAnchorSkill() == null ? "" : obj.getAnchorSkill();
				}
			}
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 输出Excel
	 *
	 * @param response
	 * @param title
	 * @param fileName
	 * @param sheetName
	 * @param values
	 * @throws IOException
	 */
	private void outPutExcel(HttpServletResponse response, String[] title, String fileName, String sheetName, String[][] values) throws IOException {
		// 创建HSSFWorkbook
		HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
		// 将文件存到指定位置
		this.setResponseHeader(response, fileName);
		OutputStream os = response.getOutputStream();
		wb.write(os);
		os.flush();
		os.close();
	}

	/**
	 * 发送响应流方法
	 *
	 * @param response
	 * @param fileName
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage(), ex);
		}
	}

	/**
	 * 业务员_主播广场_主播全平台、我收藏的列表_分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/allPlatformAnchorList.json")
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<Anchor>> allPlatformAnchorList(HttpServletRequest request) {
		BaseResponseBody<BasePage<Anchor>> result = null;
		try {
			// 请求对象
			AnchorRequestVO requestVO = this.getParameterBean(AnchorRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			BasePage<Anchor> page = null;
			page = new BasePage<Anchor>(requestVO.getPageNo(), requestVO.getPageSize());
			if (userInfo.getSourceSys() == 2) { // 业务员
				if (requestVO.getType() == 2) {
					requestVO.setBusinessId(userInfo.getId());
					page = this.anchorService.myCollectAnchorListByPage(requestVO.toMap(), page);
					page = getAnchorList(page);
				} else {
					// 分页查询
					page = this.anchorService.allPlatformAnchorListByPage(requestVO.toMap(), page, userInfo);
				}
			}
			if (userInfo.getSourceSys() == 1) { // 内容平台
				/*
				 * Family family = this.familyService.selectByUserId(userInfo.getId()); requestVO.setFamilyId(family.getFamilyId());
				 */
				Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
				if (dept != null) {
					// 查询体系
					Dept selectTopDept = this.selectTopDept(dept.getCode());
					// 查询体系下所有主播
					List<String> deptIdList = new ArrayList<>();
					this.selectDeptSon(selectTopDept.getCode(), deptIdList);
					if (deptIdList != null && deptIdList.size() > 0) {
						// 查询主播
						List<String> list = this.userInfoService.selectAnchorOtherAccountsByDeptIds(deptIdList);
						requestVO.setList(list);
					}
				}
				page = this.anchorService.allPlatformAnchorListByPage(requestVO.toMap(), page, userInfo);
			}
			result = new BaseResponseBody<BasePage<Anchor>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<Anchor>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	private BasePage<Anchor> getAnchorList(BasePage<Anchor> page) throws Exception {
		List<Anchor> anchorList = page.getResults();
		if (page != null && anchorList != null && anchorList.size() > 0) {
			List<String> anchorIdList = new ArrayList<>();
			for (int i = 0; i < anchorList.size(); i++) {
				anchorIdList.add(anchorList.get(i).getAnchorId());
			}
			String anchorIds = "";
			anchorIds = String.join(",", anchorIdList);
			anchorList = this.anchorService.getAnchorList(anchorIds);
		}
		page.setResults(anchorList);
		return page;
	}

	/**
	 * 主播pk选择对象列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectPkAnchorList.json")
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<Anchor>> selectPkAnchorList(HttpServletRequest request) {
		BaseResponseBody<BasePage<Anchor>> result = null;
		try {
			// 请求对象
			AnchorRequestVO requestVO = this.getParameterBean(AnchorRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			BasePage<Anchor> page = null;
			if (userInfo.getSourceSys() == 1) { // 内容平台
				page = new BasePage<Anchor>(requestVO.getPageNo(), requestVO.getPageSize());
				page = this.anchorService.allPlatformAnchorListByPage(requestVO.toMap(), page, null);
			}
			result = new BaseResponseBody<BasePage<Anchor>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<Anchor>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/anchorSave.json", method = RequestMethod.POST)
	@RequiredParams(names = {})
	public BaseResponseBody<Anchor> anchorSave(HttpServletRequest request) {
		BaseResponseBody<Anchor> result = null;
		try {
			// 请求对象
			Anchor anchor = this.getParameterBean(Anchor.class);

			if (StringUtils.isNotBlank(anchor.getId())) {
				this.anchorService.updateByPrimaryKey(anchor);
			} else {
				this.anchorService.insertSelective(anchor);
			}
			result = new BaseResponseBody<Anchor>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), anchor);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Anchor>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/anchorDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> anchorDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.anchorService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 根据主播Id查询主播信息详情
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/anchorDetails.json")
	@RequiredParams(names = { "id" }) // 主播Id
	public BaseResponseBody anchorDetails(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			Map<String, Object> resultMap = new HashMap<>();
			String id = this.getParameterString("id", null);
			if (StringUtils.isNotBlank(id)) {
				Anchor tempAnchor = this.anchorService.selectByAnchorId(id);
				String tempAnchorSignId = tempAnchor == null ? "" : tempAnchor.getAnchorSign();
				// 请求接口
				TreeMap<String, Object> paramMap = new TreeMap<>();
				Anchor anchor = new Anchor();
				paramMap.put("anchorId", id);
				Map map = QueryAppUtil.query("anchorInfoUrl", 1, paramMap);
				Integer code = Integer.parseInt(map.get("code").toString());
				if (code == 1) { // 成功
					String data = (String) map.get("data");
					// json字符串转object
					anchor = JsonUtils.parse(data, Anchor.class);
				} else {
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), "") + "msg: " + map.get("msg").toString(), null);
				}
				AnchorRelateAnnex anchorRelateAnnex = new AnchorRelateAnnex();
				// 才艺视频
				anchorRelateAnnex.setAnchorId(id);
				anchorRelateAnnex.setType(1);
				List<AnchorRelateAnnex> anchorRelateAnnexVidoList = this.anchorRelateAnnexService.selectList(anchorRelateAnnex);
				// 图库
				anchorRelateAnnex.setType(2);
				List<AnchorRelateAnnex> anchorRelateAnnexPageList = this.anchorRelateAnnexService.selectList(anchorRelateAnnex);
				// 附件
				anchorRelateAnnex.setType(3);
				List<AnchorRelateAnnex> anchorRelateAnnexFileList = this.anchorRelateAnnexService.selectList(anchorRelateAnnex);
				// 新主播标识图标
				if (anchor != null) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					String nowDate = sdf.format(new Date());
					Calendar cal = Calendar.getInstance();
					if (anchor.getSignContractDate() != null) {
						String signDate = sdf.format(anchor.getSignContractDate());
						cal.setTime(sdf.parse(signDate));
						long time1 = cal.getTimeInMillis();
						cal.setTime(sdf.parse(nowDate));
						long time2 = cal.getTimeInMillis();
						long between_days = (time2 - time1) / (1000 * 3600 * 24);
						if (between_days <= 30) {
							resultMap.put("newAnchorLogo", "LOGO地址未确定！");
						}
					}
				}
				// 主播标记(分组)
				if (tempAnchorSignId != null && StringUtils.isNotEmpty(tempAnchorSignId)) {
					List<String> array = Arrays.asList(tempAnchorSignId.split(","));
					StringBuffer anchorSignNames = new StringBuffer();
					StringBuffer anchorSignIds = new StringBuffer();
					if (array != null && array.size() > 0) {
						for (String signId : array) {
							AnchorGroup anchorGroup = this.groupService.selectByPrimaryKey(signId);
							String anchorSignName = anchorGroup == null ? "" : anchorGroup.getName();
							anchorSignNames.append(anchorSignName + ",");
							anchorSignIds.append(signId + ",");
						}
					}
					anchor.setAnchorSignName(anchorSignNames.toString().substring(0, anchorSignNames.length() - 1));
					anchor.setAnchorSign(anchorSignIds.toString().substring(0, anchorSignIds.length() - 1));
				}
				// 主播分组信息
				//List<AnchorRelateGroup> anchorRelateGroupList = this.anchorRelateGroupService.selectAnchorGroupListByAnchorId(id);
				//resultMap.put("anchorRelateGroupList", anchorRelateGroupList);
				resultMap.put("anchor", anchor);
				resultMap.put("anchorRelateAnnexVidoList", anchorRelateAnnexVidoList);
				resultMap.put("anchorRelateAnnexPageList", anchorRelateAnnexPageList);
				resultMap.put("anchorRelateAnnexFileList",anchorRelateAnnexFileList);
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SELECT_SUCCESS.getMsg()), resultMap);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SELECT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 主播开播/禁播
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/anchorLiveStatus.json", method = RequestMethod.POST)
	@RequiredParams(names = { "anchorId", "status" })
	public BaseResponseBody<Boolean> anchorLiveStatus(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String anchorId = this.getParameterString("anchorId", null);
			int status = this.getParameterInteger("status", null);
			Integer type = this.getParameterInteger("type", null);
			if (type == null) {
				type = 0;
			}
			// 接口请求
			TreeMap<String, Object> paramMap = new TreeMap<>();
			paramMap.put("anchorId", anchorId);
			paramMap.put("status", status);
			paramMap.put("type", type);
			Map map = QueryAppUtil.query("anchorLiveStatusUrl", 2, paramMap);
			// System.out.println("===paramMap="+paramMap+"==map=="+map);
			Integer code = Integer.parseInt(map.get("code").toString());
			String msg = map.get("msg").toString();
			if (code == 1) { // 成功
				result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), msg, true);
			} else {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), msg, null);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.RESULT_DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 主播剔除家族
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/anchorEliminateFamily.json", method = RequestMethod.POST)
	@RequiredParams(names = { "anchorId" })
	public BaseResponseBody<Boolean> anchorEliminateFamily(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 当前登录信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 请求参数
			String anchorId = this.getParameterString("anchorId", null);
			Anchor anchor = this.anchorService.selectByAnchorId(anchorId);
			if (anchor!=null){
				//接口请求
				TreeMap<String, Object> paramMap = new TreeMap<>();
				paramMap.put("anchorId", anchorId);
				paramMap.put("familyId",anchor.getFamilyId());
				paramMap.put("userId",userInfo.getId());
				Map map = QueryAppUtil.query("anchorRejectUrl", 2, paramMap);
				Integer code = Integer.parseInt(map.get("code").toString());
				if (code == 1) { //成功
					anchor.setIsDel(1);
					this.anchorService.updateByPrimaryKeySelective(anchor);
					UserInfo userInfo1 =  this.userInfoService.selectByOtherAccount(anchorId);
					if(userInfo1!=null){
						UserInfo updateUserInfo = new UserInfo();
						updateUserInfo.setId(userInfo1.getId());
						updateUserInfo.setStatus(2);
						updateUserInfo.setUpdateTime(new Date());
						this.userInfoService.updateByPrimaryKeySelective(updateUserInfo);
					}
					result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.RESULT_DATA_SUCCESS.getMsg()), true);
				} else {
					String msg=map.get("msg").toString();
					if(code==6)
					{
						msg="该公会没有该主播";
					}
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(),msg, null);

				}
			}else {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(),  UserResponseMsg.RESULT_DATA_ERROR.getMsg()), null);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.RESULT_DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}


	/**
	 *  分页查询 主播艺人薪资结算列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectAnchorSalarySettlementList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<Anchor>> selectAnchorSalarySettlementList(HttpServletRequest request) {
		BaseResponseBody<BasePage<Anchor>> result = null;
		try {
			// 当前登录用户
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 请求对象
			AnchorRequestVO requestVO = this.getParameterBean(AnchorRequestVO.class);
			// 计算结算周期的开始时间
			if(requestVO.getSettlementPeriod()==null){
				requestVO.setSettlementPeriod(7);
			}
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DATE,-requestVO.getSettlementPeriod());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String startTime = sdf.format(cal.getTime());

			if (userInfo.getType() == 6 || userInfo.getType() == 11 ) {
				requestVO.setAnchorId(userInfo.getOtherAccount()==null?"":userInfo.getOtherAccount());
			} else {
				Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
				List<String> deptList = new ArrayList<>();
				if (dept != null) {
					selectSonId(dept.getCode(), deptList);
					List<String> salesmanIds = this.userInfoService.selectAnchorOtherIdsByDeptIds(deptList);
					if(StringUtils.isNotBlank(userInfo.getOtherAccount())){
						salesmanIds.add(userInfo.getOtherAccount());
					}
					if(salesmanIds.size()==0){
						salesmanIds.add("");
					}
					requestVO.setAnchorIdList(salesmanIds);
				}
			}

			// 分页查询
			BasePage<Anchor> page = new BasePage<Anchor>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.anchorService.selectAnchorSalarySettlementByPage(requestVO.toMap(), page);
			Map<String,Object> map = new HashMap<>();
			for (Anchor anchor:page.getResults()) {
				map.put("anchorId",anchor.getAnchorId());
				map.put("startTime",startTime);
				map.put("type",3);
				BigDecimal videoRoomAmount  = this.playerRelateConsumeService.selectTotalAmountByMap(map);
				map.put("type",4);
				BigDecimal voiceRoomAmount  = this.playerRelateConsumeService.selectTotalAmountByMap(map);
				anchor.setVideoRoomAmount(videoRoomAmount);
				anchor.setVoiceRoomAmount(voiceRoomAmount);
				anchor.setSettlementPeriod(requestVO.getSettlementPeriod());

				// 查询部门名称
				Dept dept = this.deptService.selectByPrimaryKey(anchor.getDeptId());
				if(dept!=null){
					anchor.setChannelName(dept.getName());
				}

				// 查询自带粉充值金额
				BigDecimal amount = this.anchorRelateByoFansService.selectAmountByAnchorId(anchor.getAnchorId());
				anchor.setAnchorRelateByoFansAmount(amount);
			}
			result = new BaseResponseBody<BasePage<Anchor>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<Anchor>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}


	/**
	 * 主播艺人薪资结算导出Excel
	 *
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/anchorSalarySettlementListExcel.json")
	public void anchorSalarySettlementListExcel(HttpServletRequest request, HttpServletResponse response) {
		try {

			// 当前登录用户
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			AnchorRequestVO requestVO = this.getParameterBean(AnchorRequestVO.class);
			// 计算结算周期的开始时间
			if(requestVO.getSettlementPeriod()==null){
				requestVO.setSettlementPeriod(7);
			}
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DATE,-requestVO.getSettlementPeriod());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String startTime = sdf.format(cal.getTime());

			// 判断层级关系
			if (userInfo.getType() == 6 || userInfo.getType() == 11 ) {
				requestVO.setAnchorId(userInfo.getOtherAccount()==null?"":userInfo.getOtherAccount());
			} else {
				Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
				List<String> deptList = new ArrayList<>();
				if (dept != null) {
					selectSonId(dept.getCode(), deptList);
					List<String> salesmanIds = this.userInfoService.selectAnchorOtherIdsByDeptIds(deptList);
					if(StringUtils.isNotBlank(userInfo.getOtherAccount())){
						salesmanIds.add(userInfo.getOtherAccount());
					}
					if(salesmanIds.size()==0){
						salesmanIds.add("");
					}
					requestVO.setAnchorIdList(salesmanIds);
				}
			}

			// 查询数据
			List<Anchor> list = this.anchorService.selectAnchorSalarySettlementList(requestVO.toMap());
			Map<String,Object> map = new HashMap<>();
			for (Anchor anchor:list) {
				map.put("anchorId",anchor.getAnchorId());
				map.put("startTime",startTime);
				//map.put("type",3);
				BigDecimal totalAmount  = this.playerRelateConsumeService.selectTotalAmountByMap(map);
				anchor.setTotalAmount(totalAmount);
				//map.put("type",4);
				//BigDecimal voiceRoomAmount  = this.playerRelateConsumeService.selectTotalAmountByMap(map);
				//anchor.setVideoRoomAmount(videoRoomAmount);
				//anchor.setVoiceRoomAmount(voiceRoomAmount);

				// 查询部门名称
				Dept dept = this.deptService.selectByPrimaryKey(anchor.getDeptId());
				if(dept!=null){
					anchor.setChannelName(dept.getName());
				}
			}

			// excel标题
			String[] title = { "频道名称", "日期","流水周期（业绩流水）","姓名", "主播id", "艺名","主播级别" , "业绩流水", "自刷金",
					"扣除自刷金业绩", "业绩结算比例", "业绩结算金额 ", "总流水合计", "合计结算金额", "过级奖励","税前本次应发总金额",
			        "扣税点","税后本次应发金额","本次缓发金额","缓发合计","补发金额","税后本次实发金额","用户名","身份证","手机号码",
					"银行卡账号","开户行（*省*市支行）","备注"};
			// excel文件名
			String fileName = "艺人薪资结算.xls";
			// sheet名
			String sheetName = "艺人薪资结算";
			String[][] values = new String[list.size()][];

			SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
			String today = sim.format(new Date());
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					values[i] = new String[title.length];
					Anchor obj = list.get(i);
					values[i][0] = obj.getChannelName() == null ? "" : obj.getChannelName();
					values[i][1] = today;
					values[i][2] = requestVO.getSettlementPeriod()+"";
					values[i][4] = obj.getAnchorId() == null ? "" : obj.getAnchorId();
					values[i][5] = obj.getAnchorNickName() == null ? "" : obj.getAnchorNickName();
					/*
					 * if(obj.getSignContractType() == 0){ values[i][4] = "对公主播"; }else if(obj.getSignContractType() == 1){ values[i][4] = "对私主播"; }else { values[i][4] = " "; }
					 */
					values[i][7] = obj.getTotalAmount() == null ? "" : obj.getTotalAmount().toEngineeringString();
					values[i][22] = obj.getName() == null ? "" : obj.getName();
					values[i][23] = obj.getIdCardNum() == null ? "" : obj.getIdCardNum();
					values[i][24] = obj.getPhone() == null ? "" : obj.getPhone();
					values[i][25] = obj.getBankAccount() == null ? "" : obj.getBankAccount();
					values[i][26] = obj.getBank() == null ? "" : obj.getBank();
				}
			}
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}


	/**
	 * 查询所有的子集id
	 *
	 * @param parentCode
	 * @param list
	 * @throws Exception
	 */
	private void selectDeptSon(String parentCode, List<String> list) throws Exception {
		List<Dept> deptList = this.deptService.selectByParentCode(parentCode);

		if (deptList != null) {
			for (Dept dept1 : deptList) {
				list.add(dept1.getId());
				selectDeptSon(dept1.getCode(), list);
			}
		}
	}

	/**
	 * 递归查找体系
	 *
	 * @return
	 */
	private Dept selectTopDept(String code) throws Exception {
		Dept dept = this.deptService.selectByCode(code);
		if (dept.getType() == 1) {
			return dept;
		} else {
			return selectTopDept(dept.getParentCode());
		}
	}

	/**
	 * 查询组织下的部门
	 *
	 * @param code
	 * @param list
	 * @throws Exception
	 */
	private void selectSonId(String code, List<String> list) throws Exception {
		List<Dept> deptList = this.deptService.selectByParentCode(code);
		if (deptList != null) {
			for (Dept dept1 : deptList) {
				list.add(dept1.getId());
				selectSonId(dept1.getCode(), list);
			}
		}
	}
}
